package com.team06.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team06.login.dao.UserMapper;
import com.team06.login.dao.UserRoleMapper;
import com.team06.login.entity.Role;
import com.team06.login.entity.User;
import com.team06.login.entity.UserRole;
import com.team06.login.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, UserRoleMapper userRoleMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public List<User> listAllUsers() {
        List<User> users = list();
        users.forEach(user -> {
            List<Role> roles = userMapper.selectRolesByUserId(user.getId());
            user.setRoles(roles);
        });
        return users;
    }

    @Override
    @Transactional
    public boolean deleteUserById(Long id) {
        // 先删除用户角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, id));
        // 再删除用户
        return removeById(id);
    }



    @Override
    @Transactional
    public void removeAllRolesFromUser(Long userId) {
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userId));
    }

    @Override
    public List<Role> getUserRoles(Long userId) {
        return userMapper.selectRolesByUserId(userId);
    }

    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roles = userMapper.selectRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }



    @Override
    public boolean existsByUsername(String username) {
        return lambdaQuery().eq(User::getUsername, username).exists();
    }

    @Override
    public boolean existsByEmail(String email) {
        return lambdaQuery().eq(User::getEmail, email).exists();
    }


    @Override
    public List<User> searchByUsername(String username) {
        return lambdaQuery()
                .like(User::getUsername, username)
                .list()
                .stream()
                .peek(user -> user.setRoles(userMapper.selectRolesByUserId(user.getId())))
                .collect(Collectors.toList());
    }

    // 其他原有方法保持不变...
    @Override
    @Transactional
    public void assignRolesToUser(Long userId, List<Long> roleIds) {
        try {
            log.info("为用户ID: {} 分配角色: {}", userId, roleIds);
            removeAllRolesFromUser(userId);

            if (roleIds != null && !roleIds.isEmpty()) {
                List<UserRole> userRoles = roleIds.stream()
                        .map(roleId -> {
                            UserRole userRole = new UserRole();
                            userRole.setUserId(userId);
                            userRole.setRoleId(roleId);
                            return userRole;
                        })
                        .collect(Collectors.toList());

                userRoleMapper.insertBatch(userRoles);
                log.info("角色分配完成");
            }
        } catch (Exception e) {
            log.error("分配角色失败", e);
            throw e;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(User user) {
        // 1. 验证数据
        if (user.getUsername() == null || user.getPassword() == null) {
            log.error("用户名或密码为空");
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        // 2. 检查密码是否已加密
        if (!user.getPassword().startsWith("$2a$")) { // BCrypt加密密码的特征
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        // 3. 设置默认状态和默认头像
        user.setEnabledStatus(1);
        if (user.getAvatar() == null) {
            user.setAvatar("/avatars/default.jpg");
        }

        // 4. 保存用户
        log.info("执行用户插入操作，用户名: {}", user.getUsername());
        boolean saved = super.save(user);

        // 5. 验证主键生成
        if (saved && user.getId() == null) {
            log.error("用户保存成功但未生成ID，检查达梦数据库自增主键配置");
            throw new RuntimeException("主键生成失败");
        }

        // 6. 分配角色（同一事务）
        if (saved) {
            log.info("开始分配角色，用户ID: {}", user.getId());
            this.assignRolesToUser(user.getId(), List.of(2L)); // 默认分配普通用户角色
        }

        return saved;
    }
    @Override
    public User findByEmail(String email) {
        return lambdaQuery().eq(User::getEmail, email).one();
    }
}